﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using personalplaner.business.enums;
using personalplaner.common.controls;
using personalplaner.common.mvvm;
using personalplaner.common.mvvm.commands;
using personalplaner.controls;
using personalplaner.gui.common;
using personalplaner.gui.mainview.views;
using personalplaner.business;
using personalplaner.common.mvvm.mediator;
using personalplaner.servicemodel.dataaccess;

namespace personalplaner.viewmodels
{
	public class MainWindowViewModel : BaseViewModel, IMainWindowDisplayContainer
	{
		bool IsLoaded;

		public MainWindowViewModel(DependencyObject parent)
            : base(parent)
        {
			personalplaner.common.mvvm.common.ServiceLocator.RegisterGlobalService<IMainWindowDisplayContainer>(this);
		}

		public void Load()
		{
			if (IsLoaded)
				return;

			AddMenuContentItem(enDisplayItemType.MainPlanView, new ViewControler());
			IsLoaded = true;
		}

		#region Interface IMainWindowDisplayContainer

		public void AddMenuContentItem(enDisplayItemType key, UserControl ctrl, bool overwrite = false)
		{
			if (Items.ContainsKey(key) && overwrite)
				Items.Remove(key);

            if (!Items.ContainsKey(key))
            {
                Items.Add(key, ctrl);
                DisplayabelHosts[enDisplayHost.MenuDisplay].AddItem(key, ctrl, overwrite);
            }
            //if (!DisplayHostMap.ContainsKey(key))
            //    DisplayHostMap.Add(key, enDisplayHost.MenuDisplay);
			SelectItem(key);

			//UserControl itm = null;
			//if (!Items.ContainsKey(key))
			//{
			//    itm = new MenuContainerControl
			//              {
			//                  PresentableContent = ctrl
			//              };
			//    Items.Add(key, itm);
			//}
			//else
			//    itm = Items[key];

			//SelectedItem = itm;
		}

		//public void AddSimpleContentItem(enDisplayItemType key, UserControl ctrl, bool overwrite = false)
		public void AddSimpleContentItem(enDisplayItemType key, FrameworkElement ctrl, bool overwrite = false)
		{
			if (Items.ContainsKey(key) && overwrite)
				Items.Remove(key);

            if (!Items.ContainsKey(key))
            {
                Items.Add(key, ctrl);
                DisplayabelHosts[enDisplayHost.Simpledisplay].AddItem(key, ctrl, overwrite);
            }
            //if (!DisplayHostMap.ContainsKey(key))
            //    DisplayHostMap.Add(key, enDisplayHost.Simpledisplay);
			SelectItem(key);


			//UserControl itm = null;
			//if (!Items.ContainsKey(key))
			//{
			//    itm = new SimpleContainerControl
			//              {
			//                  PresentableContent = ctrl
			//              };
			//    Items.Add(key, itm);
			//}
			//else
			//    itm = Items[key];

			//SelectedItem = itm;
		}

		public bool ContainesItem(enDisplayItemType key)
		{
			return Items.ContainsKey(key);
		}

		/// <summary>
		/// selects the item that is associated with the key
		/// </summary>
		/// <param name="key">key of the item to be selected</param>
		/// <param name="silent">if false the last item will be added to the history of controls for moving backwards</param>
		public void SelectItem(enDisplayItemType key, bool silent = false)
		{
			if (!Items.ContainsKey(key))
				return;

			ControlContainer item = null;

            if (DisplayabelHosts[enDisplayHost.Simpledisplay].ContainesItem(key))
            {
				if (DisplayabelHosts[enDisplayHost.Simpledisplay].ContainesItem(key))
					item = DisplayabelHosts[enDisplayHost.Simpledisplay];

				//if (DisplayabelHosts[enDisplayHost.Simpledisplay].SelectControl(key))
				//    SelectedItem = DisplayabelHosts[enDisplayHost.Simpledisplay];

				//if (DisplayabelHosts[enDisplayHost.Simpledisplay].ContainesItem(key))
				//{
				//    SelectedItem = DisplayabelHosts[enDisplayHost.Simpledisplay];
				//    SelectedItem.SelectControl(key);
				//}

            }
            else if (DisplayabelHosts[enDisplayHost.MenuDisplay].ContainesItem(key))
            {
				if (DisplayabelHosts[enDisplayHost.MenuDisplay].ContainesItem(key))
					item = DisplayabelHosts[enDisplayHost.MenuDisplay];

				//if (DisplayabelHosts[enDisplayHost.MenuDisplay].SelectControl(key))
				//    SelectedItem = DisplayabelHosts[enDisplayHost.MenuDisplay];

				//if (DisplayabelHosts[enDisplayHost.MenuDisplay].ContainesItem(key))
				//{
				//    SelectedItem = DisplayabelHosts[enDisplayHost.MenuDisplay];
				//    SelectedItem.SelectControl(key);
				//}
            }

			if (item == null)
				return;

			if (_selecteditem != null && !silent)
			{
				_selecteditem.IsSelected = false;

				foreach (var k in Items.Keys)
					if (Items[k] == _selecteditem.SelectedItem)
						History.Add(k);
			}

			SelectedItem = item;
			SelectedItem.SelectControl(key);
		}

		public void MoveToPreviousView(/*bool removeView = false*/)
		{
			if (History.Count <= 0)
				return;

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = true;

			if (SelectedItem != null)
			{
				var uc = SelectedItem.SelectedItem as UserControl;
				if (uc != null)
				{
					var vm = uc.DataContext as BaseViewModel;
					if (vm != null)
					{
						vm.Unload();
					}
				}
			}

			SelectItem(History[History.Count - 1], true);
			History.RemoveAt(History.Count - 1);
		}

        //public void StartWait()
        //{
        //    var wnd = Parent as MainWindow;
        //    if (wnd == null)
        //        return;

        //    wnd.StartWait();
        //}

        //public void StopWait()
        //{
        //    var wnd = Parent as MainWindow;
        //    if (wnd == null)
        //        return;

        //    wnd.StopWait();
        //}

        bool _isWaitVisible;
        public bool IsWaitVisible
        {
            get
            {
                return _isWaitVisible;
            }
            set
            {
                var wnd = Parent as MainWindow;
                if (wnd == null)
                    return;

                if (value)
                    wnd.StartWait();
                else
                    wnd.StopWait();

                _isWaitVisible = value;
            }
        }


		#endregion

		#region Properties

		//Dictionary<enDisplayItemType, UserControl> _items;
		//public Dictionary<enDisplayItemType, UserControl> Items
		//{
		//    get
		//    {
		//        if (_items == null)
		//            _items = new Dictionary<enDisplayItemType, UserControl>();

		//        return _items;
		//    }
		//}
		Dictionary<enDisplayItemType, FrameworkElement> _items;
		public Dictionary<enDisplayItemType, FrameworkElement> Items
		{
			get
			{
				if (_items == null)
					_items = new Dictionary<enDisplayItemType, FrameworkElement>();

				return _items;
			}
		}

        ControlContainer _selecteditem;
        public ControlContainer SelectedItem
		{
			get { return _selecteditem; }
			set
			{

				//if (_selecteditem != null)
				//{
				//    _selecteditem.IsSelected = false;

				//    foreach (var key in Items.Keys)
				//        if (Items[key] == _selecteditem.SelectedItem)
				//            History.Add(key);
				//}

				_selecteditem = value;
                _selecteditem.IsSelected = true;
				_selecteditem.DataContext = this;
				RaisePropertyChanged("SelectedItem");
			}
		}

		List<enDisplayItemType> _history;
		public List<enDisplayItemType> History
		{
			get
			{
				if (_history == null)
					_history = new List<enDisplayItemType>();
				return _history;
			}
		}

        //Dictionary<enDisplayItemType, enDisplayHost> _displayHostMap;
        //public Dictionary<enDisplayItemType, enDisplayHost> DisplayHostMap
        //{
        //    get
        //    {
        //        if (_displayHostMap == null)
        //            _displayHostMap = new Dictionary<enDisplayItemType, enDisplayHost>();
        //        return _displayHostMap;
        //    }
        //}

        Dictionary<enDisplayHost, ControlContainer> _displayabelHosts;
        public Dictionary<enDisplayHost, ControlContainer> DisplayabelHosts
        {
            get
            {
                if (_displayabelHosts == null)
                {
                    _displayabelHosts = new Dictionary<enDisplayHost, ControlContainer>();
					//_displayabelHosts.Add(enDisplayHost.MenuDisplay, new MenuContainerControl { DataContext = this });
					_displayabelHosts.Add(enDisplayHost.MenuDisplay, new MenuControlContainer { DataContext = this });
					//_displayabelHosts.Add(enDisplayHost.Simpledisplay, new SimpleContainerControl { DataContext = this });
					_displayabelHosts.Add(enDisplayHost.Simpledisplay, new SimpleControlContainer { DataContext = this });
                }
                return _displayabelHosts;
            }
        }

        string _database;
        public string Database
        {
            get
            {
                return _database;
            }
            set
            {
                _database = value;
                RaisePropertyChanged("Database");
                RaisePropertyChanged("ShowDatabaseName");
            }
        }

        [MediatorMessageSink("SettingsRefresh")]
        public void SettingsRefresh()
        {
            RaisePropertyChanged("ShowDatabaseName");
        }

        public bool ShowDatabaseName
        {
            get
            {
                var da = GetService<IOptionsDataAccess>();
                if (da == null)
                    return false;
                return da.ShowDatabaseName;
            }
        }

		public string Version
		{
			get
			{
				return "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
			}
		}

		#endregion

		#region Commands

		ICommand _moveBackCommand;
		public ICommand MoveBackCommand
		{
			get
			{
				if (_moveBackCommand == null)
					_moveBackCommand = new RelayCommand(OnMoveBack, parameter => History.Count > 0);
				return _moveBackCommand;
			}
		}

		public void OnMoveBack(object parameter)
		{
			MoveToPreviousView();

			//if (History.Count <= 0)
			//    return;

			//SelectItem(History[History.Count - 1]);
			//History.RemoveAt(History.Count - 1);
		}

		#endregion

		
	}
}
